<template>
  <view class="page-container">
    <!-- 头部筛选栏 -->
    <view class="header-filter">
      <view 
        class="filter-item" 
        :class="{active: statusFilter === 'all'}" 
        @click="setStatusFilter('all')"
      >全部</view>
      <view 
        class="filter-item" 
        :class="{active: statusFilter === 'delivering'}" 
        @click="setStatusFilter('delivering')"
      >进行中</view>
      <view 
        class="filter-item" 
        :class="{active: statusFilter === 'completed'}" 
        @click="setStatusFilter('completed')"
      >已完成</view>
      <view 
        class="filter-item" 
        :class="{active: statusFilter === 'cancelled'}" 
        @click="setStatusFilter('cancelled')"
      >已取消</view>
    </view>
    <!-- 订单容器 -->
    <view class="order-container">
      <!-- 加载状态 -->
      <view class="loading-mask" v-if="loading">
        <text>加载中...</text>
      </view>
      <!-- 订单列表 -->
      <view class="order-list">
        <!-- 空状态提示 -->
        <view class="empty-list" v-if="!loading && filteredOrders.length === 0">
          <text>暂无订单记录</text>
        </view>
        <!-- 订单项 -->
        <view 
          v-for="(order, index) in filteredOrders" 
          :key="index" 
          class="order-item"
        >
          <!-- 新增的创建时间显示区域 -->
          <view class="order-creation-time">
            <text>{{ order.data[0].createTime || '未知时间' }}</text>
          </view>
          <view class="store-info">
            <text class="store-name">{{ getShopName(order.data[0].shopId) }}</text>
            <text class="order-status">{{ getStatusText(order.status) }}</text>
          </view>
          <view class="product-list">
            <!-- 修正图片绑定，确保使用正确的属性 -->
            <image 
              class="product-image" 
              :src="productObj.product.img" 
              mode="aspectFill" 
              v-for="(productObj, pIndex) in order.data[0].products || []" 
              :key="pIndex"
            ></image>
          </view>
          <view class="order-footer">
            <text class="total-price">
              共{{ order.data[0].products.length || 0 }}件 合计：¥{{ calculateTotal(order.data[0].products || []).toFixed(2) }}
            </text>
            <view class="order-actions">
              <text 
                v-if="order.status === 'delivering'" 
                class="action-btn confirm-btn" 
                @click="confirmReceipt(order.id)"
              >确认收货</text>
              <text 
                v-if="order.status === 'delivering'" 
                class="action-btn cancel-btn" 
                @click="cancelOrder(order.id)"
              >取消订单</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
import axios from 'axios';
import config from '../config.js';
export default {
  data() {
    return {
      orders: [],
      shops: [],
      statusFilter: 'all',
      loading: true
    };
  },
  computed: {
    filteredOrders() {
      console.log('filteredOrders计算属性执行，orders:', this.orders);
      return this.orders.filter(order => 
        this.statusFilter === 'all' || order.status === this.statusFilter
      );
    }
  },
  methods: {
    confirmReceipt(orderId) {
      const order = this.orders.find(item => item.id === orderId);
      if (order) {
        order.status = 'completed';
        uni.showToast({
          title: '已确认收货',
          icon: 'success'
        });
      }
    },
    // 取消订单方法（纯前端修改）
    cancelOrder(orderId) {
      const order = this.orders.find(item => item.id === orderId);
      if (order) {
        order.status = 'cancelled';
        uni.showToast({
          title: '已取消订单',
          icon: 'success'
        });
      }
    },
    // 获取订单数据
    async fetchOrders() {
      try {
        const res = await axios.get(config.api_host+'/orders', {
          params: { userId: uni.getStorageSync('ID') }
        });
        console.log('获取订单数据成功，返回数据:', res.data);
        // 确保处理返回数据的逻辑正确
        this.orders = (res.data || []).map(order => ({
         ...order,
          status: order.status || 'delivering' // 如果订单没有状态字段，默认设为配送中
        }));
      } catch (error) {
        console.error('获取订单数据失败:', error);
      } finally {
        this.loading = false;
      }
    },
    // 获取店铺数据
    async fetchShops() {
      try {
        const res = await axios.get(config.api_host+'/data');
        console.log('获取店铺数据成功，返回数据:', res.data);
        this.shops = res.data || [];
      } catch (error) {
        console.error('店铺加载失败:', error);
      }
    },
    calculateTotal(items) {
        console.log('calculateTotal items:', items);
        return items.reduce((sum, item) => {
            console.log('item.product.price:', item.product.price, 'item.orderSales:', item.orderSales);
            return sum + (item.product.price * item.orderSales);
        }, 0);
    },
    getShopName(shopId) {
      if (shopId === undefined) {
        return '未知商家';
      }
      const shop = this.shops.find(s => s._id === shopId.toString());
      return shop? shop.name : '沃尔玛';
    },
    getShopImage(shopId) {
      if (shopId === undefined) {
        return '';
      }
      const shop = this.shops.find(s => s._id === shopId.toString());
      return shop?.imgUrl || '';
    },
    getStatusText(status) {
      // 默认显示为配送中
      const statusMap = {
        pending: '待付款',
        delivering: '配送中',
        completed: '已完成',
        cancelled: '已取消'
      };
      return statusMap[status] || '配送中';
    },
    setStatusFilter(value) {
      this.statusFilter = value;
    }
  },
  onLoad(options) {
    if (options.orderData) {
      try {
        const orderData = JSON.parse(decodeURIComponent(options.orderData));
        // 这里假设将接收到的订单数据添加到 orders 中，你可能需要根据实际逻辑调整
        this.orders.push({
          id: Date.now(), // 简单生成一个唯一 id
          status: 'delivering',
          data: [orderData]
        });
      } catch (error) {
        console.error('解析订单数据失败:', error);
      }
    }
  },
  onShow() {
    // 确保每次进入页面都能获取最新的订单数据
    this.fetchOrders();
    this.fetchShops();
  }
};
</script>
<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
}
.header-filter {
  display: flex;
  justify-content: space-around;
  background: #ffffff;
  padding: 10px 0;
  border-bottom: 1px solid #e0e0e0;
}
.filter-item {
  font-size: 14px;
  color: #333333;
  padding: 5px 10px;
  transition: all 0.3s ease;
}
.filter-item.active {
  color: #007AFF;
  border-bottom: 2px solid #007AFF;
}
.order-container {
  padding: 15px;
  background-color: #ffffff;
}
/* 加载状态 */
.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}
/* 空状态 */
.empty-list {
  text-align: center;
  padding: 100px 0;
  color: #999999;
  font-size: 16px;
}
/* 订单项 */
.order-item {
  background: #ffffff;
  border-radius: 8px;
  margin-bottom: 15px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
/* 新增的创建时间样式 */
.order-creation-time {
  margin-bottom: 10px;
  color: #777777;
  font-size: 14px;
}
.store-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.store-name {
  font-size: 24px;
  color: #000000;
}
.order-status {
  color: #999999;
  font-size: 20px;
}
/* 商品项 */
.product-image {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  margin-right: 10px;
}
.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.price-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.product-quantity {
  color: #666666;
  font-size: 14px;
}
/* 订单底部 */
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 5px;
  border-top: none;
}
.total-price {
  color: #FF5500;
  font-size: 16px;
  font-weight: bold;
}
/* 操作按钮 */
.order-actions {
  display: flex;
  gap: 10px;
}
.action-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s ease;
}
.confirm-btn {
  border: 1px solid #007AFF;
  color: #007AFF;
}
.confirm-btn:hover {
  background-color: #007AFF;
  color: #ffffff;
}
.cancel-btn {
  border: 1px solid #999999;
  color: #666666;
}
.cancel-btn:hover {
  background-color: #999999;
  color: #ffffff;
}
</style>